import _ from "lodash"

export const getScrollWidth = () => {
	let div = document.createElement("div")
	div.style.cssText = `
		display: block;
		position: absolute;
		width: 100px;
		height: 100px;
		padding: 0;
		margin: 0;
		border: none;
		opacity: 0;
		overflow-y: scroll;
		z-index: -99;
	`
	document.body.append(div)
	const { clientWidth, offsetWidth } = div
	div.remove()
	div = null
	return offsetWidth - clientWidth
}

/**
 * 监听元素尺寸变化
 * @param {HTMLElement} el 元素
 * @param {Function} func 触发函数
 * @returns {ResizeObserver} 监听对象
 */
export const onResize = (el, func) => {
	if (!_.isElement(el) || !_.isFunction(func)) return null

	let observer = null,
		resizeStart = false,
		resizeEnd = false,
		event = {
			width: el.clientWidth,
			height: el.clientHeight,
			target: el,
			type: null,
		}

	const emit = data => {
		event = {
			...event,
			...data,
		}
		func(event)
	}

	const touch = entries => {
		// for (const entry of entries) {
		// 	console.log(entry)
		// }
		if (!resizeEnd) {
			resizeEnd = true

			requestAnimationFrame(() => {
				resizeEnd = false
				if (event.width !== el.clientWidth || event.height !== el.clientHeight) {
					if (!resizeStart) {
						resizeStart = true
						emit({
							width: event.clientWidth,
							height: event.clientHeight,
							type: "start-resize",
						})
					}
					emit({
						width: el.clientWidth,
						height: el.clientHeight,
						type: "on-resizing",
					})
				}

				requestAnimationFrame(() => {
					if (!resizeEnd && resizeStart) {
						resizeEnd = true
						emit({
							width: el.clientWidth,
							height: el.clientHeight,
							type: "end-resize",
						})
						resizeStart = false
						resizeEnd = false
					}
				})
			})
		}
	}

	observer = new ResizeObserver(touch)
	observer.observe(el)

	observer.destroy = () => {
		observer.disconnect()
		observer = null
		return observer
	}

	return observer
}
